package net.zhengxinyun.performance.service.indicators;

import net.zhengxinyun.performance.Util.StringUtils;
import net.zhengxinyun.performance.dto.SixTownDTO;
import net.zhengxinyun.performance.entity.SixIndicatorsEntity;
import net.zhengxinyun.performance.entity.SixTownEntity;
import net.zhengxinyun.performance.filter.*;
import net.zhengxinyun.performance.mapper.Indicators.SixIndicatorsEntityMapper;
import net.zhengxinyun.performance.mapper.Indicators.SixScoreEntityMapper;
import net.zhengxinyun.performance.mapper.Indicators.SixTownEntityMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.*;

/**
 * Created by hyp1202 on 2018/11/27.
 */
@Service
public class SixIndicatorsServiceImpl  implements  SixIndicatorsService{
    
    private SixIndicatorsEntityMapper sixIndicatorsEntityMapper;
    private SixTownEntityMapper sixTownEntityMapper;
    private SixTownService sixTownService;
    private SixScoreEntityMapper sixScoreEntityMapper;

    @Autowired
    public SixIndicatorsServiceImpl(SixIndicatorsEntityMapper sixIndicatorsEntityMapper, SixTownEntityMapper sixTownEntityMapper, SixTownService sixTownService, SixScoreEntityMapper sixScoreEntityMapper) {
        this.sixIndicatorsEntityMapper = sixIndicatorsEntityMapper;
        this.sixTownEntityMapper = sixTownEntityMapper;
        this.sixTownService = sixTownService;
        this.sixScoreEntityMapper = sixScoreEntityMapper;
    }

    @Override
    @Transactional
    public String delete(SixIndicatorsEntity sixIndicatorsEntity) {
        int a ;
        SixIndicatorsEntity entity = sixIndicatorsEntityMapper.selectByPrimaryKey(sixIndicatorsEntity.getId());
        if ("一级指标".equals(entity.getIndexType())){
            SixIndicatorsFilter sixIndicatorsFilter = new SixIndicatorsFilter();
            sixIndicatorsFilter.setSuperiorIndexId(entity.getId().toString());
            List<SixIndicatorsFilter> list = sixIndicatorsEntityMapper.query(sixIndicatorsFilter);
            for (SixIndicatorsFilter filter:list) {
                a = sixIndicatorsEntityMapper.deleteByPrimaryKey(filter.getId());
                if (a == 0){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return "下属指标删除失败";
                }
                sixScoreEntityMapper.deleteByIndexId(filter.getId().toString());
            }
        }
        a = sixIndicatorsEntityMapper.deleteByPrimaryKey(sixIndicatorsEntity.getId());
        if (a == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "删除失败,请联系管理员";
        }
        return "删除成功";
    }

    @Override
    @Transactional
    public String update(SixIndicatorsEntity sixIndicatorsEntity, List<SixTownEntity> townList) {
        if ("二级指标".equals(sixIndicatorsEntity.getIndexType())) {
//            List<SixTownEntity> list = Util.townUtil(townDTO);
            setSuperId(sixIndicatorsEntity);
            int i = sixIndicatorsEntityMapper.updateByPrimaryKeySelective(sixIndicatorsEntity);
            if (i != 1) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return "更新失败,请联系管理员";
            }
            int a;
            for (SixTownEntity sixTownEntity : townList) {
                sixTownEntity.setIndexId(sixIndicatorsEntity.getId().toString());
                a = sixTownEntityMapper.updateByNameAndIndexId(sixTownEntity);
                if (a != 1) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return "更新失败,请联系管理员";
                }
            }
        } else {
            int i = sixIndicatorsEntityMapper.updateByPrimaryKeySelective(sixIndicatorsEntity);
            if (i != 1) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return "更新失败,请联系管理员";
            }
        }
        return "更新成功";
    }

    /**
     * 单个指标添加
     *
     * @param sixIndicatorsEntity
     * @param townList
     * @return
     */
    @Override
    @Transactional
    public String insert(SixIndicatorsEntity sixIndicatorsEntity, List<SixTownEntity> townList) {
        //如果没有乡镇就直接添加
        if (townList == null) {
            setSuperId(sixIndicatorsEntity);
            long i = sixIndicatorsEntityMapper.insert(sixIndicatorsEntity);
            if (i != 1) {
                //触发事务回滚
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return "添加失败,请联系管理员";
            }
            return "添加成功";
        }
        //如果是二级指标
        if ("二级指标".equals(sixIndicatorsEntity.getIndexType())) {
            setSuperId(sixIndicatorsEntity);
            long i = sixIndicatorsEntityMapper.insert(sixIndicatorsEntity);
            if (i != 1) {
                //触发事务回滚
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return "添加失败,请联系管理员";
            }
            sixTownService.insert(sixIndicatorsEntity, townList);
//            Long lastId = sixIndicatorsEntity.getId();
//            for (SixTownEntity townEntity : townList) {
//                townEntity.setIndexId(lastId.toString());
//                long a = sixSixTownEntityMapper.insert(townEntity);
//                if (a != 1) {
//                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                    return "添加失败,请联系管理员";
//                }
//            }
//            return "添加成功";
        }
//        else if ("一级指标".equals(sixIndicatorsEntity.getIndexType())){
//            long i =  sixIndicatorsEntityMapper.insert(sixIndicatorsEntity);
//            if (i!= 1){
//                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                return "添加失败。请联系管理员";
//            }
//            return "添加成功";
//        }
        return "添加成功";
    }

    /**
     * 批量添加
     *
     * @param list
     * @return
     */
    @Override
    @Transactional
    public String ListInsert(List<SixTownDTO> list) {
        list = removeDuplicate(list);
        for (SixTownDTO townDTO : list) {
            SixIndicatorsEntity sixIndicatorsEntity = townDTO.getSixIndicatorsEntity();
            List<SixTownEntity> townList = townDTO.getSixTownList();
            if ("二级指标".equals(sixIndicatorsEntity.getIndexType())) {
                setSuperId(sixIndicatorsEntity);
                long i = sixIndicatorsEntityMapper.insert(sixIndicatorsEntity);
                if (i != 1) {
                    //触发事务回滚
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return "添加失败,请联系管理员";
                }
                sixTownService.insert(sixIndicatorsEntity, townList);
            } else if ("一级指标".equals(sixIndicatorsEntity.getIndexType())) {
                SixIndicatorsFilter filter = sixIndicatorsEntityMapper.queryByNameAndTime(sixIndicatorsEntity);
                if (filter != null){
                    continue;
                }
                long i = sixIndicatorsEntityMapper.insert(sixIndicatorsEntity);
                if (i != 1) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return "添加失败。请联系管理员";
                }
            }
        }
        return "添加成功";
    }

    /**
     * 查询二级指标及其对应的乡镇
     *
     * @param sixIndicatorsFilter
     * @return
     */
    public List<Map<String, Object>> querySec(SixIndicatorsFilter sixIndicatorsFilter) {
        List<SixIndicatorsFilter> list = sixIndicatorsEntityMapper.query(sixIndicatorsFilter);
        List<Map<String, Object>> indexList = new ArrayList<>();
        SixIndicatorsEntity entity ;
        for (SixIndicatorsFilter filter : list) {
            Map<String, Object> indexMap = new LinkedHashMap<>();
            indexMap.put("id", filter.getId());
            indexMap.put("indexType", filter.getIndexType());
            indexMap.put("leadUnit", filter.getLeadUnit());
            indexMap.put("indexName", filter.getIndexName());
            indexMap.put("responsibilityUnit", filter.getResponsibilityUnit());
            indexMap.put("direction", filter.getDirection());
            indexMap.put("weight", Double.parseDouble(filter.getWeight()));
            indexMap.put("dateTime",filter.getDateTime());
            indexMap.put("mainUnit",filter.getMainUnit());
            indexMap.put("endTime",filter.getEndTime());
            indexMap.put("warnType",filter.getWarnType());
            //把对应的上级指标名返回给前端
            if (StringUtils.isNotBlank(filter.getSuperiorIndexId())){
                entity = sixIndicatorsEntityMapper.selectByPrimaryKey(Long.valueOf(filter.getSuperiorIndexId()));
                if (entity != null){
                    indexMap.put("superiorIndexId", entity.getIndexName());
                }
            }
            List<SixTownFilter> townList = sixTownEntityMapper.queryByIndexId(filter.getId().toString());
            for (SixTownFilter townFilter : townList) {
                if (StringUtils.isNotBlank(townFilter.getWeight())){
                    indexMap.put(townFilter.getTownName(), Double.parseDouble(townFilter.getWeight()));
                }else {
                    indexMap.put(townFilter.getTownName(), null);
                }
            }
            indexList.add(indexMap);
        }
        return indexList;
    }

    @Override
    public List<Map<String, Object>> queryIndexMap(List<SixIndicatorsFilter> list) {
        List<Map<String, Object>> indexList = new ArrayList<>();
        SixIndicatorsFilter townIndicatorsFilter = new SixIndicatorsFilter();
        for (SixIndicatorsFilter filter:list) {
            HashMap indexMap = new HashMap();
            indexMap.put("firstName",filter);
            townIndicatorsFilter.setIndexType("");
            townIndicatorsFilter.setSuperiorIndexId(filter.getId().toString());
            List<SixIndicatorsFilter> secondIndexList = query(townIndicatorsFilter);
            indexMap.put("secondIndex",secondIndexList);
            indexList.add(indexMap);
        }
        return indexList;
    }

    @Override
    public List<SixIndicatorsFilter> query(SixIndicatorsFilter townIndicatorsFilter) {
        return sixIndicatorsEntityMapper.query(townIndicatorsFilter);
    }

    @Override
    public Integer queryForCount(SixIndicatorsFilter townIndicatorsFilter) {
        return sixIndicatorsEntityMapper.queryForCount(townIndicatorsFilter);
    }

    /**
     * 设置上级指标id
     *
     * @param sixIndicatorsEntity
     * @return
     */
    public SixIndicatorsEntity setSuperId(SixIndicatorsEntity sixIndicatorsEntity) {
        if (StringUtils.isNotBlank(sixIndicatorsEntity.getSuperiorIndexId())) {
            String id = sixIndicatorsEntityMapper.queryIdBySuperName(sixIndicatorsEntity);
            sixIndicatorsEntity.setSuperiorIndexId(id);
        }
        return sixIndicatorsEntity;
    }

    @Override
    public List<SixIndicatorsFilter> indexTown(IndexFilter indexFilter) {
        List<SixIndicatorsFilter> list ;
        if (StringUtils.isBlank(indexFilter.getDateTime()) && StringUtils.isBlank(indexFilter.getMonthTime())){
            SixScoreFilter sixScoreFilter = sixScoreEntityMapper.queryForNewTime();
            indexFilter.setDateTime(sixScoreFilter.getDateTime());
            indexFilter.setMonthTime(sixScoreFilter.getMonthTime());
            list = sixIndicatorsEntityMapper.indexSix(indexFilter);
        }else {
            list = sixIndicatorsEntityMapper.indexSix(indexFilter);
        }
//        Collections.sort(list, new Comparator<SixIndicatorsFilter>() {
//            @Override
//            public int compare(SixIndicatorsFilter o1, SixIndicatorsFilter o2) {
//                if (Integer.parseInt(o1.getRank()) > Integer.parseInt(o2.getRank())){
//                    return 1;
//                }else {
//                    return -1;
//                }
//            }
//        });
        return list;
    }

    @Override
    public List<Map<String, Object>> getIndexMap(List<SixIndicatorsFilter> list) {
        List<Map<String, Object>> indexList = new ArrayList<>();
        SixIndicatorsFilter sixIndicatorsFilter = new SixIndicatorsFilter();
        List<SixIndicatorsFilter> copyList = new ArrayList<>();
        for (SixIndicatorsFilter filter : list) {
            HashMap indexMap = new HashMap();
            indexMap.put("firstName", filter);
            sixIndicatorsFilter.setIndexType("");
            sixIndicatorsFilter.setSuperiorIndexId(filter.getId().toString());
            List<SixIndicatorsFilter> secondIndexList = query(sixIndicatorsFilter);
            Iterator<SixIndicatorsFilter> it = secondIndexList.iterator();
            while (it.hasNext()) {
                SixIndicatorsFilter c = it.next();
                if (StringUtils.isBlank(c.getLeadUnit())) {
                    copyList.add(c);
                    it.remove();
                }
            }
            for (SixIndicatorsFilter f:copyList) {
                sixIndicatorsFilter.setSuperiorIndexId(f.getId().toString());
                List<SixIndicatorsFilter> sonList = query(sixIndicatorsFilter);
                secondIndexList.addAll(sonList);
            }
            indexMap.put("secondIndex", secondIndexList);
            indexList.add(indexMap);
        }
        return indexList;
    }

    @Override
    public String setEndTime(List<SixIndicatorsEntity> list, String endTime,String warnType) {
        for (SixIndicatorsEntity entity:list) {
            entity.setEndTime(endTime);
            entity.setWarnType(warnType);
            int i = sixIndicatorsEntityMapper.updateByPrimaryKeySelective(entity);
            if ( i == 0){
                return "设置失败";
            }
        }
        return "设置成功";
    }

    @Override
    public List<SixIndicatorsFilter> queryWarn(String today, String dateTime) {
        SixIndicatorsFilter sixIndicatorsFilter = new SixIndicatorsFilter();
        sixIndicatorsFilter.setEndTime(today);
        sixIndicatorsFilter.setDateTime(dateTime);
        List<SixIndicatorsFilter> list = sixIndicatorsEntityMapper.queryWarn(sixIndicatorsFilter);
        return list;
    }

    /**
     * list集合根据上级指标id，指标名对元素去重
     * @param list
     * @return
     */
    private List<SixTownDTO> removeDuplicate(List<SixTownDTO> list){
        Set<SixTownDTO> set = new TreeSet<SixTownDTO>(new Comparator<SixTownDTO>() {
            @Override
            public int compare(SixTownDTO o1, SixTownDTO o2) {
                //字符串,则按照asicc码升序排列
                if (o1.getSixIndicatorsEntity().getIndexName().equals(o2.getSixIndicatorsEntity().getIndexName())
                        && o1.getSixIndicatorsEntity().getSuperiorIndexId().equals(o2.getSixIndicatorsEntity().getSuperiorIndexId())){
                    return 0;
                }
                return 1;
            }
        });
        set.addAll(list);
        return new ArrayList<SixTownDTO>(set);
    }
}
